package com.zx.article.manager.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zx.article.manager.model.ManagerModel;
import com.zx.article.manager.service.IManagerService;
import com.zx.article.manager.service.impl.ManagerServiceImpl;
import com.zx.article.util.FmtRequest;

@WebServlet("/ManagerServlet")
public class ManagerServlet extends HttpServlet {

	private static final long serialVersionUID = 3884976847717298156L;
	private FmtRequest fmtRequest = new FmtRequest();
	private IManagerService managerService = new ManagerServiceImpl();

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String result = "未实现方法";
		String action = request.getParameter("action");
		switch (action) {
		case "reg":
			result = reg(request);
			break;
		case "login":
			result = login(request);
			break;
		case "logout":
			logout(request, response);
			break;
		case "updata":
			result = updata(request);
			break;
		default:
			break;
		}
		fmtRequest.write(response.getWriter(), result);
	}

	private String updata(HttpServletRequest request) {
		ManagerModel managerModel = new ManagerModel();
		managerModel.setAccount(request.getParameter("account"));
		managerModel.setNickName(request.getParameter("nickName"));
		return managerService.updata(managerModel, request);
	}

	private void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
		request.getSession().removeAttribute("user");
		response.sendRedirect(request.getContextPath() + "/web/login.jsp");
	}

	private String login(HttpServletRequest request) {
		String authcode = request.getParameter("authcode");
		Object attribute = request.getSession().getAttribute("authcode");
		if (!authcode.equals(attribute)) {
			return "authcode";
		}
		ManagerModel parseModel = fmtRequest.parseModel(request, ManagerModel.class);
		return managerService.login(parseModel, request);
	}

	private String reg(HttpServletRequest request) {
		if (!request.getParameter("password").equals(request.getParameter("realPassword"))) {
			return "different";
		}
		ManagerModel parseModel = fmtRequest.parseModel(request, ManagerModel.class);
		return managerService.reg(parseModel);
	}

}
